/*
 * main.c
 *
 *  Created on: 23/11/2011
 *      Author: utn_so
 */

#include <fcntl.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>

#define TAM_ARCH	16
#define TAM			8

int main(void){

	int archivo;
	char *ptr;
	char str[TAM + 1];
	size_t tamanio;

	int arch;
	struct stat buf;

	if ((arch = open("./big_fat32.disk", O_RDWR)) == -1){
		perror("Error 1\n");
		return 1;
	}

	/*if (fseek(arch, 0, SEEK_END)){
		perror("Error 1\n");
		return 1;
	}

	if ((tamanio = ftell(arch) * sizeof(char)) == -1){
		perror("Error 1\n");
		return 1;
	}*/

	if (fstat(arch, &buf) == -1){
		perror("Error 1\n");
		return 1;
	}

	tamanio = buf.st_size;

	close(arch);

	printf("%d\n", tamanio);

	if ((archivo = open("./archivo.txt", O_RDWR)) == -1){
		printf("Error 1\n");
		return 1;
	}

	/*ftruncate(archivo, TAM_ARCH);*/

	if ((ptr = mmap(0, TAM_ARCH, PROT_READ | PROT_WRITE, MAP_SHARED/*MAP_PRIVATE*/, archivo, 0)) == MAP_FAILED){
		printf("Error 2\n");
		return 1;
	}

	if (posix_madvise(ptr, TAM_ARCH, POSIX_MADV_SEQUENTIAL) != 0){
		printf("Error 3\n");
		return 1;
	}

	memcpy(str, ptr, TAM);
	str[TAM] = '\0';
	memcpy(ptr, "12345678", TAM);

	memcpy(str, ptr, TAM);
	str[TAM] = '\0';

	if ((msync(ptr, TAM, MS_SYNC)) == -1){
		printf("Error 4\n");
		return 1;
	}

	if ((munmap(ptr, TAM_ARCH)) == -1){
		printf("Error 5\n");
		return 1;
	}

	if ((close(archivo)) == -1){
		printf("Error 6\n");
		return 1;
	}

	return 0;
}
